package client;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;

import client.application.AboutAction;
import client.application.ConnectAction;
import client.application.DisconnectAction;
import client.application.QuitAction;

/*
 * Author : Mohamed Delhomme
 */

public class ClientView extends JFrame implements ActionListener {

	static final private String ADD = "add";
	static final private String REMOVE = "remove";
	static final private String UP = "up";
	static final private String DOWN = "down";

	static public Vector<String> serversList = new Vector<String>();
	static public Vector<String> servicesList = new Vector<String>();
	static public Vector<String[]> listSongs = new Vector<String[]>();
	static public Vector<String[]> localPlaylist = new Vector<String[]>();
	static public Vector<String[]> globalPlaylist = new Vector<String[]>();

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public Remote remote;
	public ClientUpdateChecker checker;

	private JSplitPane mainPanel;
	private JPanel leftPanel;
	private JPanel rightPanel;

	private JMenuBar menuBar;
	private JMenu fileMenu;
	private JMenu helpMenu;
	public JMenuItem connectItem;
	public JMenuItem disconnectItem;
	private JMenuItem aboutItem;
	private JMenuItem quitItem;

	public JButton buttonConnectServer;
	public JButton buttonDisconnectServer;
	public JLabel labelLinkServer;

	public TextArea dialogue;

	public JList listSongsAvailable;
	public JList listSongsChoosen;
	public JList listGlobal;

	public ClientView() throws IOException {
		super();

		remote = new Remote();
		remote.showHandshaking(true);

		build();
	}

	private void build() {

		// general properties for the main window
		setTitle("Uss Player");
		setSize(800, 300);
		setLocationRelativeTo(null); // center the window on the screen
		setResizable(true); // avoiding resizing of the window
		// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		addWindowListener(new WindowListener() {

			@Override
			public void windowActivated(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowClosed(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowClosing(WindowEvent e) {
				checker.stop();
			}

			@Override
			public void windowDeactivated(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowDeiconified(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowIconified(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void windowOpened(WindowEvent e) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		leftPanel = new JPanel();
		rightPanel = new JPanel();

		mainPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel,
				rightPanel);
		mainPanel.setOneTouchExpandable(true);
		mainPanel.setContinuousLayout(true);

		add(mainPanel);

		// #######################################################
		// Setting the menu bar
		// #######################################################

		menuBar = new JMenuBar();
		fileMenu = new JMenu("File");
		helpMenu = new JMenu("Help");

		connectItem = new JMenuItem(new ConnectAction(this, "Connect"));
		disconnectItem = new JMenuItem(new DisconnectAction(this, "Disconnect"));
		disconnectItem.setEnabled(false);

		aboutItem = new JMenuItem(new AboutAction(this, "About Uss Player"));
		quitItem = new JMenuItem(new QuitAction(this, "Quit"));

		fileMenu.add(connectItem);
		// fileMenu.add(disconnectItem);
		fileMenu.addSeparator();
		fileMenu.add(quitItem);

		helpMenu.add(aboutItem);

		menuBar.add(fileMenu);
		menuBar.add(helpMenu);

		setJMenuBar(menuBar);

		// #######################################################
		// Setting the left panel
		// #######################################################

		leftPanel.setLayout(new BorderLayout());

		dialogue = new TextArea(50, 30);
		dialogue.setEditable(false);
		dialogue.setBackground(new Color(40, 40, 95));
		dialogue.setForeground(new Color(0, 128, 255));

		JTabbedPane tabServersServices = new JTabbedPane();
		tabServersServices.add("Dialogue", dialogue);

		JPanel linkPanel = new JPanel();
		linkPanel.setLayout(new BoxLayout(linkPanel, BoxLayout.Y_AXIS));

		JPanel connectPanel = new JPanel(new BorderLayout());
		JPanel disconnectPanel = new JPanel(new BorderLayout());

		buttonConnectServer = new JButton(new ConnectAction(this,
				"Connect To Server"));
		buttonDisconnectServer = new JButton(new DisconnectAction(this,
				"Disconnect From Server"));
		buttonDisconnectServer.setEnabled(false);

		connectPanel.add(buttonConnectServer, BorderLayout.CENTER);
		// disconnectPanel.add(buttonDisconnectServer, BorderLayout.CENTER);

		linkPanel.add(connectPanel);
		linkPanel.add(disconnectPanel);

		labelLinkServer = new JLabel(
				"   Status : you are currently disconnected   ");

		leftPanel.add(tabServersServices, BorderLayout.CENTER);
		leftPanel.add(linkPanel, BorderLayout.NORTH);
		leftPanel.add(labelLinkServer, BorderLayout.AFTER_LAST_LINE);

		// #######################################################
		// Setting the right panel
		// #######################################################

		rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.X_AXIS));

		listSongsAvailable = new JList();
		listSongsAvailable
				.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listSongsAvailable.setVisibleRowCount(10);
		listSongsAvailable.setFixedCellHeight(20);
		listSongsAvailable.setFixedCellWidth(200);
		listSongsAvailable.setFont(new Font("Serif", Font.PLAIN, 12));
		listSongsAvailable.setBackground(new Color(40, 40, 95));
		listSongsAvailable.setForeground(new Color(0, 128, 255));

		listSongsChoosen = new JList();
		listSongsChoosen.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listSongsChoosen.setVisibleRowCount(10);
		listSongsChoosen.setFixedCellHeight(20);
		listSongsChoosen.setFixedCellWidth(200);
		listSongsChoosen.setFont(new Font("Serif", Font.PLAIN, 12));
		listSongsChoosen.setBackground(new Color(40, 40, 95));
		listSongsChoosen.setForeground(new Color(0, 128, 255));

		listGlobal = new JList();
		listGlobal.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listGlobal.setVisibleRowCount(10);
		listGlobal.setFixedCellHeight(20);
		listGlobal.setFixedCellWidth(200);
		listGlobal.setFont(new Font("Serif", Font.PLAIN, 12));
		listGlobal.setBackground(new Color(40, 40, 95));
		listGlobal.setForeground(new Color(0, 128, 255));

		JTabbedPane tabPlaylist = new JTabbedPane();
		tabPlaylist.add("Local Playlist", listSongsChoosen);
		tabPlaylist.add("Global Playlist", listGlobal);

		JScrollPane songsAvailablePanel = new JScrollPane(listSongsAvailable);
		JPanel addRemovePanel = new JPanel(new BorderLayout());
		JScrollPane playlistPanel = new JScrollPane(tabPlaylist);
		JPanel managePlaylistPanel = new JPanel(new BorderLayout());

		JPanel panel1 = new JPanel(new BorderLayout());
		JPanel panel2 = new JPanel(new BorderLayout());

		panel1.add(new JLabel("Songs Available"),
				BorderLayout.BEFORE_FIRST_LINE);
		panel1.add(songsAvailablePanel, BorderLayout.CENTER);

		panel2.add(new JLabel("Playlist"), BorderLayout.BEFORE_FIRST_LINE);
		panel2.add(playlistPanel, BorderLayout.CENTER);

		JToolBar toolBarAddRemove = new JToolBar("Add or remove songs");
		JButton button = null;

		// first button
		button = makeNavigationButton("backward", REMOVE,
				"Remove the seleted songs to the playlist", "Remove");
		toolBarAddRemove.add(button);

		// second button
		button = makeNavigationButton("forward", ADD,
				"Add the seleted songs to the playlist", "Add");
		toolBarAddRemove.add(button);

		addRemovePanel.add(toolBarAddRemove, BorderLayout.NORTH);
		addRemovePanel.add(panel1, BorderLayout.CENTER);

		JToolBar toolBarManagePlaylist = new JToolBar("Manage Playlist");

		// first button
		button = makeNavigationButton("down", DOWN, "", "Down");
		// toolBarManagePlaylist.add(button);

		// second button
		button = makeNavigationButton("up", UP, "", "Up");
		// toolBarManagePlaylist.add(button);
		managePlaylistPanel.add(toolBarManagePlaylist, BorderLayout.NORTH);
		managePlaylistPanel.add(panel2, BorderLayout.CENTER);

		rightPanel.add(addRemovePanel);
		rightPanel.add(managePlaylistPanel);

		// #######################################################
		// Running the thread
		// #######################################################

		checker = new ClientUpdateChecker(this);

		checker.start();

	} // build()

	protected JButton makeNavigationButton(String imageName,
			String actionCommand, String toolTipText, String altText) {
		// Look for the image.
		String imgLocation = "resources/" + imageName + ".JPG";
		URL imageURL = ClientView.class.getResource(imgLocation);

		// Create and initialize the button.
		JButton button = new JButton();
		button.setActionCommand(actionCommand);
		button.setToolTipText(toolTipText);
		button.addActionListener(this);

		if (imageURL != null) { // image found
			button.setIcon(new ImageIcon(imageURL, altText));
		} else { // no image found
			button.setText(altText);
			System.err.println("Resource not found: " + imgLocation);
		}

		return button;
	}

	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();

		// Handle each button.
		if (REMOVE.equals(cmd)) {
			// JOptionPane.showMessageDialog(this, "This part do not work yet");

			int selectIdx = listSongsChoosen.getSelectedIndex();
			String[] song = (String[]) listSongsChoosen.getSelectedValue();

			boolean removed = false;
			try {
				removed = remote.removeSong(song);
			} catch (RemoteException e1) {
				e1.printStackTrace();
			}

			if (removed) {
				localPlaylist.removeElement(song);
				listSongsChoosen.remove(selectIdx);
			}

		} else if (UP.equals(cmd)) {
			JOptionPane.showMessageDialog(this, "This part do not work yet");
		} else if (ADD.equals(cmd)) {

			int selectIdx = listSongsAvailable.getSelectedIndex();
			String[] song = listSongs.get(selectIdx);

			if (null != song) {
				try {
					remote.selectSong(song);
				} catch (RemoteException e1) {
					e1.printStackTrace();
				}

				localPlaylist.addElement(song);
				Vector<String> list = getStringSong(localPlaylist);
				listSongsChoosen.setListData(localPlaylist);

			} else {
				JOptionPane.showMessageDialog(this,
						"No song selected : you have to select a song !");
			}
		} else if (DOWN.equals(cmd)) {
			JOptionPane.showMessageDialog(this, "This part do not work yet");
		}

	}

	public Vector<String> getStringSong(Vector<String[]> listSongs) {
		Vector<String> listOfSongs = new Vector<String>();
		for (Iterator iterator = listSongs.iterator(); iterator.hasNext();) {
			String[] strings = (String[]) iterator.next();
			String label = new String(strings[0]);
			for (int i = 1; i < strings.length; i++) {
				label += " - " + strings[i];
			}
			listOfSongs.add(label);
		}

		return listOfSongs;
	}

}
